<template>
  <div class="top drag"></div>
  <!--  <div class="iconfont">群聊信息</div>-->
  <el-button
    class="no-drag"
    style="position: absolute; right: 200px; top: 0"
    type="primary"
    @click="test"
    >点击
  </el-button>
  <el-scrollbar ref="scrollbarRef" class="main-content" @scroll="scroll">
    <div id="a">
      <div class="load">
        <img v-if="showLoad" alt="" src="../../assets/img/load.gif" width="20" />
      </div>
      <div
        v-for="(item, index) in val2"
        :key="index"
        :id="`test${item.id}`"
        :num="item.id"
        class="b"
      >
        {{ item }}
      </div>
    </div>
  </el-scrollbar>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'

const scrollbarRef = ref() // 滚动组件的ref引用
const val = ref([])
const val2 = computed(() => {
  let val2 = val.value
  val2.sort((a, b) => {
    return parseInt(b.id) - parseInt(a.id)
  })
  return val2
})

const showLoad = ref(false)

const test = () => {
  document.querySelector('#test13').scrollIntoView()
}

const scroll = ({ scrollTop }) => {
  console.log(document.querySelector("[num='0']")) // 查询属性num == 0 元素 element对象
  console.log(document.querySelector("[num='0']").getBoundingClientRect())

  if (scrollTop === 0) {
    // 到顶加载 添加数据
    if (val.value[0].value === 300) {
      // 没有信息了
      return
    }
    showLoad.value = true
    console.log(val.value[0])
    setTimeout(() => {
      for (let i = val.value[0].value; i < val.value[0].value + 10; i++) {
        if (i > 300) {
          break
        }
        val.value.push({ id: i, value: i })
      }

      setTimeout(() => {
        if (val.value[0].value > 300) {
          scrollbarRef.value.setScrollTop(0) // 定位滚动条的位置
        }
        scrollbarRef.value.setScrollTop(500) // 定位滚动条的位置
      }, 1)
      showLoad.value = false
    }, 2000)
  }
}
onMounted(() => {
  // 加载数据
  for (let i = 0; i < 51; i++) {
    val.value.push({ id: i, value: i })
  }

  setTimeout(() => {
    scrollbarRef.value.setScrollTop(100) //定位滚动条的位置
  }, 1)
})
</script>

<style lang="scss" scoped>
.top {
  height: 60px;
}

.iconfont {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 100px;
  color: #ddd;
  height: calc(100vh - 122px);
}

.main-content {
  order: -1;
  height: calc(100vh - 60px);
}

.load {
  z-index: 1;
  display: flex;
  justify-content: center;
}
</style>
